/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			mdic_basic.cc
  \date			Sep 2011
  \author		TNick

  \brief		Contains the implementation for basic interaction in mdi window


  Copyright (c) 2011, Nicu Tofan
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 * Neither the name of the copyright holder nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL NICU TOFAN BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include	<QMessageBox>
#include	<QCloseEvent>
#include	<QPageSetupDialog>
#include	<QPrintDialog>
#include	<QPrintPreviewDialog>

#include	<sheet/ETSheetView.h>

#include	"mdichild.h"
#include	"ui_mdichild.h"

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */


/* ------------------------------------------------------------------------- */
void                MdiChild::newFile           ( void )
{
	static int sequenceNumber = 1;

	is_untitled = true;
	cur_file = tr("document%1.txt").arg(sequenceNumber++);
	setWindowTitle(cur_file + "[*]");
	/*connect(document(), SIGNAL(contentsChanged()),
   this, SLOT(documentWasModified()));*/
	sheet = ETSheet::newVisible(QString(), this);
	if (sheet == NULL)
	{
		close();
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::loadFile          (const QString &fileName)
{
	QFile file(fileName);
	if (!file.open(QFile::ReadOnly | QFile::Text)) {
		QMessageBox::warning(this, tr("Error"),
							 tr("Cannot read file %1:\n%2.")
							 .arg(fileName)
							 .arg(file.errorString()));
		return false;
	}


	setCurrentFile(fileName);

	/*connect(document(), SIGNAL(contentsChanged()),
   this, SLOT(documentWasModified()));*/

	sheet = ETSheet::newVisible(fileName, this);
	if (sheet == NULL)
	{
		close();
		return false;
	}
	else
	{
		//static_cast<ETSheetView*>(widget())->setScene(sheet);
		return true;
	}

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::save              ( void )
{
	if (is_untitled)
	{
		return saveAs();
	}
	else
	{
		return saveFile(cur_file);
	}
}/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::saveAs            ( void )
{

	QFileDialog::Options options;
	QString selectedFilter;
	QString fileName = QFileDialog::getSaveFileName(
				this,
				tr("Select the location ..."),
				"",
				tr("All Files (*);;Text Files (*.txt)"),
				&selectedFilter,
				options);
	if (!fileName.isEmpty())
	{
		if (saveFile(fileName))
		{
			emit nameChanged();
			return true;
		}
	}
	return false;

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::saveFile          (const QString &fileName)
{

	sheet->saveXMLFile(fileName);
	setCurrentFile(fileName);
	return true;

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::closeEvent        (QCloseEvent *event)
{
	if (maybeSave())
	{
		event->accept();
		//is_closed = true;
		emit docClosed(this);
	}
	else
	{
		event->ignore();
	}
	deleteLater();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::maybeSave         ( void )
{
	if (is_modified)
	{
		QMessageBox::StandardButton ret;
		ret = QMessageBox::warning(this, tr("Tell me..."),
								   tr("'%1' has been modified.\n"
									  "Do you want to save your changes?")
								   .arg(userFriendlyCurrentFile()),
								   QMessageBox::Save | QMessageBox::Discard
								   | QMessageBox::Cancel);
		if (ret == QMessageBox::Save)
			return save();
		else if (ret == QMessageBox::Cancel)
			return false;
	}
	return true;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::setCurrentFile    (const QString &fileName)
{
	cur_file = QFileInfo(fileName).canonicalFilePath();
	is_untitled = false;
	is_modified = false;
	setWindowModified(false);
	setWindowTitle(userFriendlyCurrentFile() + "[*]");
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::pageSetupDialog   ( void )
{
#ifndef QT_NO_PRINTER
	QPageSetupDialog set_pg(&printer, this);
	set_pg.exec();
#else
	QMessageBox::warning(this, tr("Error"),
						 tr("Print support was disabled at build time."));
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::printDialog       ( void )
{
#ifndef QT_NO_PRINTER
	QPrintDialog dialog(&printer, this);
	dialog.setWindowTitle(tr("Print Document"));
	/*if (editor.textCursor().hasSelection())
  dialog.addEnabledOption(QAbstractPrintDialog::PrintSelection);*/
	if (dialog.exec() != QDialog::Accepted)
		return;
	print();
#else
	QMessageBox::warning(this, tr("Error"),
						 tr("Print support was disabled at build time."));
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::print             ( void )
{
#ifndef QT_NO_PRINTER
	QPainter painter;
	painter.begin(&printer);
	/*
 for (int page = 0; page < numberOfPages; ++page) {

  // Use the painter to draw on the page.

  if (page != lastPage)
   printer.newPage();
 }
*/
	painter.end();
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::printPreviewDialog    ( void )
{
#ifndef QT_NO_PRINTER

	QPrintPreviewDialog preview(&printer, this);
	preview.setWindowFlags( Qt::Window );

	/*
 connect(&preview, SIGNAL(paintRequested(QPrinter *)),
   SLOT(printPreview(QPrinter *)));

 */
	preview.exec();

#else
	QMessageBox::warning(this, tr("Error"),
						 tr("Print support was disabled at build time."));
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::undo            	( void )
{
	if (sheet != NULL)
	{
		sheet->performUndo();
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::redo            	( void )
{
	if (sheet != NULL)
	{
		sheet->performRedo();
	}
}
/* ========================================================================= */


/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
